package hoodoos.rule.script.jython;


import hoodoos.rule.api.Rule;
import org.python.core.PyBaseCode;
import org.python.core.PyClass;
import org.python.core.PyFunction;
import org.python.core.PyObject;
import org.python.util.PythonInterpreter;

public class JythonLoader {

  private final PythonInterpreter pythonInterpreter;

  public JythonLoader() {
    super();
    this.pythonInterpreter = new PythonInterpreter();
  }

  public Rule loadRule(String code, String ruleName) {
    pythonInterpreter.exec(code);
    PyClass pyClass = (PyClass) pythonInterpreter.get(ruleName);
    return new JythonRule(ruleName, pyClass);
  }

  private boolean checkMethod(PyClass pyClass, String methodName, String[] argsFilter) {
    PyObject pyObject = pyClass.__dict__.__finditem__(methodName);
    if (pyObject instanceof PyFunction) {
      String[] argNames = ((PyBaseCode) ((PyFunction) pyObject).__code__).co_varnames;
      for (int i = 0; i < argsFilter.length; i++) {
        if (!argNames[i].equals(argsFilter[i])) {
          return false;
        }
      }
      return true;
    }
    else {
      return false;
    }
  }

}
